import { User, Shield, Bell, Key } from 'lucide-react';
import { useLanguage } from '@kernelproxy/i18n';
import { useState, useEffect } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import { authService } from '../../services/auth';
import { useToast } from '../../contexts/ToastContext';

const Settings = () => {
  const { language } = useLanguage();
  const { user, checkAuth } = useAuth();
  const toast = useToast();
  const [notifications, setNotifications] = useState({
    email: true,
    lowBalance: true,
    serviceAlert: true,
    newsletter: false,
  });

  // Security state
  const [twoFactorEnabled, setTwoFactorEnabled] = useState(false);
  const [isTogglingTwoFactor, setIsTogglingTwoFactor] = useState(false);
  const [showQRModal, setShowQRModal] = useState(false);
  const [qrCodeUri, setQrCodeUri] = useState('');
  const [totpSecret, setTotpSecret] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [verificationError, setVerificationError] = useState('');

  // Change Password state
  const [showChangePasswordModal, setShowChangePasswordModal] = useState(false);
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmNewPassword, setConfirmNewPassword] = useState('');
  const [isChangingPassword, setIsChangingPassword] = useState(false);
  const [passwordError, setPasswordError] = useState('');

  // Profile state
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [isEditingUsername, setIsEditingUsername] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [saveMessage, setSaveMessage] = useState('');

  // Load user data and 2FA status
  useEffect(() => {
    if (user) {
      setUsername(user.name || '');
      setEmail(user.email || '');
      // If user doesn't have a name, enable editing by default
      if (!user.name) {
        setIsEditingUsername(true);
      }
    }
  }, [user]);

  // Check 2FA status on mount
  useEffect(() => {
    const check2FAStatus = async () => {
      try {
        const result = await authService.check2FAStatus();
        if (result.success && result.enabled) {
          setTwoFactorEnabled(true);
        }
      } catch (error) {
        console.error('Failed to check 2FA status:', error);
      }
    };

    check2FAStatus();
  }, []);

  const handleSaveProfile = async () => {
    if (!username.trim()) {
      setSaveMessage(language === 'zh-CN' ? '用户名不能为空' : 'Username cannot be empty');
      return;
    }

    setIsSaving(true);
    setSaveMessage('');

    try {
      const result = await authService.updateName(username.trim());
      
      if (result.success) {
        setSaveMessage(language === 'zh-CN' ? '保存成功！' : 'Saved successfully!');
        setIsEditingUsername(false);
        // Refresh user data
        await checkAuth();
        setTimeout(() => setSaveMessage(''), 3000);
      } else {
        setSaveMessage(language === 'zh-CN' ? '保存失败，请重试' : 'Failed to save, please try again');
      }
    } catch (error) {
      setSaveMessage(language === 'zh-CN' ? '保存失败，请重试' : 'Failed to save, please try again');
    } finally {
      setIsSaving(false);
    }
  };

  const handleToggleTwoFactor = async () => {
    if (!twoFactorEnabled) {
      // Enable 2FA - show QR code modal
      setIsTogglingTwoFactor(true);
      try {
        const result = await authService.enable2FA();
        if (result.success && result.uri && result.secret) {
          setQrCodeUri(result.uri);
          setTotpSecret(result.secret);
          setShowQRModal(true);
        } else {
          console.error('Failed to enable 2FA:', result.error);
          toast.error(language === 'zh-CN' ? '启用2FA失败，请重试' : 'Failed to enable 2FA, please try again');
        }
      } catch (error) {
        console.error('Failed to enable 2FA:', error);
        toast.error(language === 'zh-CN' ? '启用2FA失败，请重试' : 'Failed to enable 2FA, please try again');
      } finally {
        setIsTogglingTwoFactor(false);
      }
    } else {
      // Disable 2FA - show confirmation
      const confirmed = window.confirm(
        language === 'zh-CN' 
          ? '确定要禁用双因素验证吗？这将降低您的账户安全性。' 
          : 'Are you sure you want to disable two-factor authentication? This will reduce your account security.'
      );
      
      if (confirmed) {
        setIsTogglingTwoFactor(true);
        try {
          const result = await authService.disable2FA();
          if (result.success) {
            setTwoFactorEnabled(false);
            toast.success(language === 'zh-CN' ? '2FA已成功禁用' : '2FA disabled successfully');
          } else {
            console.error('Failed to disable 2FA:', result.error);
            toast.error(language === 'zh-CN' ? '禁用2FA失败，请重试' : 'Failed to disable 2FA, please try again');
          }
        } catch (error) {
          console.error('Failed to disable 2FA:', error);
          toast.error(language === 'zh-CN' ? '禁用2FA失败，请重试' : 'Failed to disable 2FA, please try again');
        } finally {
          setIsTogglingTwoFactor(false);
        }
      }
    }
  };

  const handleVerify2FASetup = async () => {
    if (verificationCode.length !== 6) {
      setVerificationError(language === 'zh-CN' ? '请输入6位验证码' : 'Please enter 6-digit code');
      return;
    }

    setIsTogglingTwoFactor(true);
    setVerificationError('');

    try {
      const result = await authService.verify2FASetup(verificationCode);
      if (result.success) {
        setTwoFactorEnabled(true);
        setShowQRModal(false);
        setVerificationCode('');
        setQrCodeUri('');
        setTotpSecret('');
        toast.success(language === 'zh-CN' ? '2FA已成功启用！' : '2FA enabled successfully!');
      } else {
        setVerificationError(language === 'zh-CN' ? '验证码错误，请重试' : 'Invalid code, please try again');
      }
    } catch (error: any) {
      console.error('Failed to verify 2FA setup:', error);
      if (error.message?.includes('Invalid token') || error.message?.includes('invalid secret')) {
        setVerificationError(language === 'zh-CN' ? '验证码错误或已过期' : 'Invalid or expired code');
      } else {
        setVerificationError(language === 'zh-CN' ? '验证失败，请重试' : 'Verification failed, please try again');
      }
    } finally {
      setIsTogglingTwoFactor(false);
    }
  };

  // Handle change password
  const handleChangePassword = async () => {
    setPasswordError('');

    // Validation
    if (!currentPassword || !newPassword || !confirmNewPassword) {
      setPasswordError(language === 'zh-CN' ? '请填写所有字段' : 'Please fill in all fields');
      return;
    }

    if (newPassword !== confirmNewPassword) {
      setPasswordError(language === 'zh-CN' ? '新密码不匹配' : 'New passwords do not match');
      return;
    }

    if (newPassword.length < 8) {
      setPasswordError(language === 'zh-CN' ? '密码至少需要8个字符' : 'Password must be at least 8 characters');
      return;
    }

    if (newPassword === currentPassword) {
      setPasswordError(language === 'zh-CN' ? '新密码不能与当前密码相同' : 'New password cannot be the same as current password');
      return;
    }

    setIsChangingPassword(true);

    try {
      const result = await authService.updatePassword(newPassword, currentPassword);
      if (result.success) {
        toast.success(language === 'zh-CN' ? '密码修改成功！' : 'Password changed successfully!');
        setShowChangePasswordModal(false);
        setCurrentPassword('');
        setNewPassword('');
        setConfirmNewPassword('');
      } else {
        const errorMsg = language === 'zh-CN' ? '当前密码错误或修改失败' : 'Current password is incorrect or change failed';
        setPasswordError(errorMsg);
        toast.error(errorMsg);
      }
    } catch (error) {
      console.error('Failed to change password:', error);
      const errorMsg = language === 'zh-CN' ? '修改密码失败，请重试' : 'Failed to change password, please try again';
      setPasswordError(errorMsg);
      toast.error(errorMsg);
    } finally {
      setIsChangingPassword(false);
    }
  };

  const handleCancelQRModal = () => {
    setShowQRModal(false);
    setVerificationCode('');
    setVerificationError('');
    setQrCodeUri('');
    setTotpSecret('');
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
          {language === 'zh-CN' ? '账户设置' : 'Account Settings'}
        </h1>
        <p className="text-gray-600 dark:text-gray-400 mt-2">
          {language === 'zh-CN' ? '管理您的账户和偏好设置' : 'Manage your account and preferences'}
        </p>
      </div>

      {/* Profile Settings */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
        <div className="flex items-center space-x-2 mb-6">
          <User className="w-5 h-5 text-blue-600 dark:text-blue-400" />
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '个人资料' : 'Profile'}
          </h2>
        </div>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {language === 'zh-CN' ? '用户名' : 'Username'}
            </label>
            <div className="flex gap-2">
              <input
                type="text"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                disabled={!isEditingUsername}
                className={`flex-1 px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 ${
                  isEditingUsername 
                    ? 'bg-white dark:bg-gray-700' 
                    : 'bg-gray-100 dark:bg-gray-900 cursor-not-allowed'
                }`}
                placeholder={language === 'zh-CN' ? '请输入用户名' : 'Enter username'}
              />
              {!isEditingUsername && user?.name && (
                <button
                  onClick={() => setIsEditingUsername(true)}
                  className="px-4 py-2 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-colors"
                >
                  {language === 'zh-CN' ? '编辑' : 'Edit'}
                </button>
              )}
            </div>
            {!user?.name && (
              <p className="mt-1 text-xs text-amber-600 dark:text-amber-400">
                {language === 'zh-CN' ? '您还未设置用户名，请填写并保存' : 'You haven\'t set a username yet, please fill and save'}
              </p>
            )}
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {language === 'zh-CN' ? '电子邮箱' : 'Email'}
            </label>
            <input
              type="email"
              value={email}
              readOnly
              className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-white cursor-not-allowed"
            />
            <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
              {language === 'zh-CN' ? '邮箱地址不可更改' : 'Email address cannot be changed'}
            </p>
          </div>
          
          {/* Save message */}
          {saveMessage && (
            <div className={`p-3 rounded-lg ${
              saveMessage.includes('成功') || saveMessage.includes('successfully')
                ? 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400'
                : 'bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-400'
            }`}>
              {saveMessage}
            </div>
          )}

          {isEditingUsername && (
            <div className="flex gap-2 justify-end">
              <button
                onClick={handleSaveProfile}
                disabled={isSaving}
                className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isSaving 
                  ? (language === 'zh-CN' ? '保存中...' : 'Saving...') 
                  : (language === 'zh-CN' ? '保存更改' : 'Save Changes')}
              </button>
              {user?.name && (
                <button
                  onClick={() => {
                    setUsername(user.name || '');
                    setIsEditingUsername(false);
                    setSaveMessage('');
                  }}
                  disabled={isSaving}
                  className="px-6 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {language === 'zh-CN' ? '取消' : 'Cancel'}
                </button>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Security Settings */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
        <div className="flex items-center space-x-2 mb-6">
          <Shield className="w-5 h-5 text-green-600 dark:text-green-400" />
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '安全设置' : 'Security'}
          </h2>
        </div>
        <div className="space-y-4">
          <div className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
            <div>
              <p className="font-medium text-gray-900 dark:text-white">
                {language === 'zh-CN' ? '双因素认证' : 'Two-Factor Authentication'}
              </p>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                {language === 'zh-CN' ? '使用2FA保护您的账户' : 'Secure your account with 2FA'}
              </p>
            </div>
            <button 
              onClick={handleToggleTwoFactor}
              disabled={isTogglingTwoFactor}
              className={`px-4 py-2 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
                twoFactorEnabled
                  ? 'bg-red-600 hover:bg-red-700 text-white'
                  : 'bg-green-600 hover:bg-green-700 text-white'
              }`}
            >
              {isTogglingTwoFactor 
                ? (language === 'zh-CN' ? '处理中...' : 'Processing...') 
                : twoFactorEnabled 
                  ? (language === 'zh-CN' ? '禁用' : 'Disable')
                  : (language === 'zh-CN' ? '启用' : 'Enable')
              }
            </button>
          </div>
          <div className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
            <div>
              <p className="font-medium text-gray-900 dark:text-white">
                {language === 'zh-CN' ? 'IP白名单' : 'IP Whitelist'}
              </p>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                {language === 'zh-CN' ? '限制访问的IP地址' : 'Restrict access by IP address'}
              </p>
            </div>
            <button className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
              {language === 'zh-CN' ? '管理' : 'Manage'}
            </button>
          </div>
          <div className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
            <div>
              <p className="font-medium text-gray-900 dark:text-white">
                {language === 'zh-CN' ? '修改密码' : 'Change Password'}
              </p>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                {language === 'zh-CN' ? '更新您的登录密码' : 'Update your login password'}
              </p>
            </div>
            <button 
              onClick={() => setShowChangePasswordModal(true)}
              className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
            >
              {language === 'zh-CN' ? '修改' : 'Change'}
            </button>
          </div>
        </div>
      </div>

      {/* API Keys */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
        <div className="flex items-center space-x-2 mb-6">
          <Key className="w-5 h-5 text-purple-600 dark:text-purple-400" />
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? 'API密钥' : 'API Keys'}
          </h2>
        </div>
        <div className="space-y-3 mb-4">
          {[
            { name: 'Production Key', key: 'sk_live_••••••••••••4567', created: '2025-08-15' },
            { name: 'Development Key', key: 'sk_test_••••••••••••8901', created: '2025-09-01' },
          ].map((apiKey, index) => (
            <div key={index} className="flex items-center justify-between p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
              <div>
                <p className="font-medium text-gray-900 dark:text-white">{apiKey.name}</p>
                <p className="text-sm font-mono text-gray-600 dark:text-gray-400">{apiKey.key}</p>
                <p className="text-xs text-gray-500 dark:text-gray-500 mt-1">
                  {language === 'zh-CN' ? '创建于' : 'Created'}: {apiKey.created}
                </p>
              </div>
              <button className="text-red-600 dark:text-red-400 hover:underline text-sm">
                {language === 'zh-CN' ? '撤销' : 'Revoke'}
              </button>
            </div>
          ))}
        </div>
        <button className="w-full py-3 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg text-gray-600 dark:text-gray-400 hover:border-purple-400 dark:hover:border-purple-500 hover:text-purple-600 dark:hover:text-purple-400 transition-colors">
          {language === 'zh-CN' ? '+ 创建新密钥' : '+ Create New Key'}
        </button>
      </div>

      {/* Notifications */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
        <div className="flex items-center space-x-2 mb-6">
          <Bell className="w-5 h-5 text-orange-600 dark:text-orange-400" />
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '通知设置' : 'Notifications'}
          </h2>
        </div>
        <div className="space-y-4">
          {[
            { key: 'email', label: language === 'zh-CN' ? '邮件通知' : 'Email Notifications' },
            { key: 'lowBalance', label: language === 'zh-CN' ? '余额预警' : 'Low Balance Alerts' },
            { key: 'serviceAlert', label: language === 'zh-CN' ? '服务告警' : 'Service Alerts' },
            { key: 'newsletter', label: language === 'zh-CN' ? '新闻通讯' : 'Newsletter' },
          ].map((item) => (
            <div key={item.key} className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
              <span className="text-gray-900 dark:text-white">{item.label}</span>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={notifications[item.key as keyof typeof notifications]}
                  onChange={(e) => setNotifications({ ...notifications, [item.key]: e.target.checked })}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
              </label>
            </div>
          ))}
        </div>
      </div>

      {/* QR Code Modal for 2FA Setup */}
      {showQRModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
            <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
              {language === 'zh-CN' ? '设置双因素验证' : 'Setup Two-Factor Authentication'}
            </h3>
            
            <div className="space-y-4">
              <p className="text-sm text-gray-600 dark:text-gray-400">
                {language === 'zh-CN' 
                  ? '1. 使用您的验证器应用（如 Google Authenticator 或 Authy）扫描下方二维码'
                  : '1. Scan the QR code below with your authenticator app (Google Authenticator or Authy)'}
              </p>

              {/* QR Code Display */}
              <div className="flex justify-center p-4 bg-white rounded-lg border-2 border-gray-200">
                {qrCodeUri ? (
                  <img 
                    src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qrCodeUri)}`}
                    alt="QR Code"
                    className="w-48 h-48"
                  />
                ) : (
                  <div className="w-48 h-48 bg-gray-100 dark:bg-gray-700 flex items-center justify-center">
                    <p className="text-gray-400">{language === 'zh-CN' ? '加载中...' : 'Loading...'}</p>
                  </div>
                )}
              </div>

              {/* Manual Entry Secret */}
              <div className="bg-gray-50 dark:bg-gray-900/50 p-3 rounded-lg">
                <p className="text-xs text-gray-600 dark:text-gray-400 mb-1">
                  {language === 'zh-CN' ? '或手动输入密钥：' : 'Or enter manually:'}
                </p>
                <code className="text-sm font-mono text-gray-900 dark:text-white break-all">
                  {totpSecret}
                </code>
              </div>

              <p className="text-sm text-gray-600 dark:text-gray-400">
                {language === 'zh-CN' 
                  ? '2. 输入验证器应用中显示的6位验证码以完成设置'
                  : '2. Enter the 6-digit code from your authenticator app to complete setup'}
              </p>

              {/* Verification Code Input */}
              <div>
                <label htmlFor="verificationCode" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {language === 'zh-CN' ? '验证码' : 'Verification Code'}
                </label>
                <input
                  id="verificationCode"
                  type="text"
                  value={verificationCode}
                  onChange={(e) => setVerificationCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                  placeholder={language === 'zh-CN' ? '输入6位验证码' : 'Enter 6-digit code'}
                  maxLength={6}
                  className="w-full px-4 py-2 text-center text-2xl tracking-widest font-mono border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white rounded-lg focus:ring-2 focus:ring-[#00d4ff] focus:border-[#00d4ff] placeholder:text-gray-400 dark:placeholder:text-gray-500 placeholder:text-lg placeholder:tracking-normal"
                />
                {verificationError && (
                  <p className="text-sm text-red-600 dark:text-red-400 mt-2">
                    {verificationError}
                  </p>
                )}
              </div>

              {/* Action Buttons */}
              <div className="flex space-x-3 mt-6">
                <button
                  onClick={handleCancelQRModal}
                  disabled={isTogglingTwoFactor}
                  className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {language === 'zh-CN' ? '取消' : 'Cancel'}
                </button>
                <button
                  onClick={handleVerify2FASetup}
                  disabled={isTogglingTwoFactor || verificationCode.length !== 6}
                  className="flex-1 px-4 py-2 bg-gradient-to-r from-[#00d4ff] to-[#0f1c3f] text-white rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isTogglingTwoFactor 
                    ? (language === 'zh-CN' ? '验证中...' : 'Verifying...') 
                    : (language === 'zh-CN' ? '验证并启用' : 'Verify & Enable')}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Change Password Modal */}
      {showChangePasswordModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
            <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
              {language === 'zh-CN' ? '修改密码' : 'Change Password'}
            </h3>
            
            <div className="space-y-4">
              {/* Current Password */}
              <div>
                <label htmlFor="currentPassword" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {language === 'zh-CN' ? '当前密码' : 'Current Password'}
                </label>
                <input
                  id="currentPassword"
                  type="password"
                  value={currentPassword}
                  onChange={(e) => setCurrentPassword(e.target.value)}
                  placeholder={language === 'zh-CN' ? '输入当前密码' : 'Enter current password'}
                  className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white rounded-lg focus:ring-2 focus:ring-[#00d4ff] focus:border-[#00d4ff] placeholder:text-gray-400 dark:placeholder:text-gray-500"
                />
              </div>

              {/* New Password */}
              <div>
                <label htmlFor="newPassword" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {language === 'zh-CN' ? '新密码' : 'New Password'}
                </label>
                <input
                  id="newPassword"
                  type="password"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  placeholder={language === 'zh-CN' ? '至少8个字符' : 'At least 8 characters'}
                  className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white rounded-lg focus:ring-2 focus:ring-[#00d4ff] focus:border-[#00d4ff] placeholder:text-gray-400 dark:placeholder:text-gray-500"
                />
              </div>

              {/* Confirm New Password */}
              <div>
                <label htmlFor="confirmNewPassword" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {language === 'zh-CN' ? '确认新密码' : 'Confirm New Password'}
                </label>
                <input
                  id="confirmNewPassword"
                  type="password"
                  value={confirmNewPassword}
                  onChange={(e) => setConfirmNewPassword(e.target.value)}
                  placeholder={language === 'zh-CN' ? '再次输入新密码' : 'Enter new password again'}
                  className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white rounded-lg focus:ring-2 focus:ring-[#00d4ff] focus:border-[#00d4ff] placeholder:text-gray-400 dark:placeholder:text-gray-500"
                />
              </div>

              {/* Error Message */}
              {passwordError && (
                <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
                  <p className="text-sm text-red-600 dark:text-red-400">{passwordError}</p>
                </div>
              )}

              {/* Action Buttons */}
              <div className="flex space-x-3 mt-6">
                <button
                  onClick={() => {
                    setShowChangePasswordModal(false);
                    setCurrentPassword('');
                    setNewPassword('');
                    setConfirmNewPassword('');
                    setPasswordError('');
                  }}
                  disabled={isChangingPassword}
                  className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {language === 'zh-CN' ? '取消' : 'Cancel'}
                </button>
                <button
                  onClick={handleChangePassword}
                  disabled={isChangingPassword || !currentPassword || !newPassword || !confirmNewPassword}
                  className="flex-1 px-4 py-2 bg-gradient-to-r from-[#00d4ff] to-[#0f1c3f] text-white rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isChangingPassword 
                    ? (language === 'zh-CN' ? '修改中...' : 'Changing...') 
                    : (language === 'zh-CN' ? '确认修改' : 'Confirm Change')}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Settings;
